<template>
  <el-dialog
    :title="textMap[type]"
    :visible.sync="_visible"
    width="550px"
    destroy-on-close
    @close="handleCloseDialog"
  >
    <!--    <div>{{ JSON.stringify(formData) }}</div>-->
    <el-form
      ref="dataForm_version"
      :rules="rules"
      :model.sync="formData"
      label-position="left"
      label-width="100px"
      style="width: 400px; margin-left:50px;"
    >
      <el-form-item label="产品名称" prop="product">
        <el-input v-model="formData.product" placeholder="请输入产品名称" @input="formData.product = formData.product !== undefined ? formData.product.trim(): ''" />
      </el-form-item>
      <el-form-item label="产品版本" prop="version">
        <el-input v-model="formData.version" placeholder="请输入产品版本" @input="formData.version = formData.version !== undefined ? formData.version.trim(): ''" />
      </el-form-item>
      <el-form-item label="标识" prop="flag">
        <el-input v-model="formData.flag" placeholder="请输入版本标识, 类型：json" />
      </el-form-item>
      <el-form-item label="上传服务器" prop="server">
        <el-select
          v-model="formData.server"
          value-key="key"
          placeholder="请选择上传服务器"
          style="width:100%"
          @change="handleServerChange"
        >
          <el-option
            v-for="item in servers"
            :key="item.key"
            :label="item.name"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上传版本包" prop="pkg">
        <el-upload
          class="upload-demo"
          :action="uploadAddress"
          :before-upload="handleUploadCheck"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-remove="handleUploadRemove"
          :file-list="uploadFileList"
          name="file"
          :data="uploadData"
          :limit="1"
          :disabled="uploadDisabled"
          style="width:100%"
        >
          <el-button size="small" type="primary" :disabled="uploadDisabled">点击上传</el-button>
          <div
            slot="tip"
            class="el-upload__tip"
            :class="{'upload-ok': uploadStatus === 1, 'upload-fail': uploadStatus === 2}"
          >{{ uploadTip }}
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="发布时间" prop="releaseTime">
        <el-date-picker
          v-model="formData.releaseTime"
          type="datetime"
          value-format="timestamp"
          placeholder="选择日期时间"
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <multi-description
          :model.sync="formData.description"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDialog">
        取消
      </el-button>
      <el-button type="primary" @click="type==='create'?createVersion():updateVersion()">
        提交
      </el-button>
    </div>
  </el-dialog>
</template>
<style scoped>
  /* 日期选择框的宽度 */
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 300px;
  }

  .upload-ok {
    color: green;
  }

  .upload-fail {
    color: red;
  }

  /deep/ .el-dialog__body {
    height: 471px;
    overflow-y: auto;
  }
</style>
<script>
import fota from '../../api/fota'
import apiConst from '../../common/js/apiConst'
import MultiDescription from './multiDescription'

export default {
  name: 'VersionCreateDialog',
  components: { MultiDescription },
  props: {
    'type': {
      type: String,
      default: function() {
        return 'create'
      }
    },
    'servers': {
      type: Array,
      default: function() {
        return []
      }
    },
    'visible': Boolean
  },
  data() {
    return {
      textMap: {
        update: '修改版本',
        create: '新增版本'
      },
      formData: { description: [] },
      uploadDefaultTip: '请选择上传服务器后，进行版本包上传！',
      uploadTip: '',
      uploadData: {},
      uploadAddress: '',
      uploadFileList: [],
      uploadStatus: 0,
      rules: []
    }
  },
  computed: {
    uploadDisabled: {
      get: function() {
        return this.formData.server === undefined ||
                this.formData.product === undefined ||
                this.formData.product.trim() === ''
      }
    },
    _visible: {
      get: function() {
        return this.visible
      },
      set: function(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    this.initRules()
  },
  mounted() {
    this.resetData()
  },
  methods: {
    resetData: function() {
      this.uploadFileList = []
      this.uploadStatus = 0
      this.uploadTip = this.uploadDefaultTip
    },
    reloadTable: function() {
      this.handleCloseDialog()
      this.$emit('callback')
    },
    createVersion() {
      const self = this
      this.$refs['dataForm_version'].validate((valid) => {
        if (valid) {
          const param = JSON.parse(JSON.stringify(this.formData))
          this.dealChangeParam(param)
          fota.insertPkg(param).then(() => {
            self.reloadTable()
            fota.notifySuccess('版本创建成功！')
          }, () => {
            this.reloadTable()
            fota.notifyError(`版本创建失败！`)
          })
        }
      })
    },
    updateVersion() {
      const self = this
      this.$refs['dataForm_version'].validate((valid) => {
        if (valid) {
          const param = JSON.parse(JSON.stringify(this.formData))
          this.dealChangeParam(param)
          fota.updatePkg(param).then(() => {
            self.reloadTable()
            fota.notifySuccess('版本修改成功！')
          }, () => {
            this.reloadTable()
            fota.notifyError(`版本修改失败！`)
          })
        }
      })
    },
    dealChangeParam(param) {
      param.server = undefined
      const newDes = {}
      for (const item of param.description) {
        newDes[item.lang] = item.description
      }
      param.description.map(item => { newDes[item.lang] = item.description })
      param.description = JSON.stringify(newDes)
    },
    handleCloseDialog() {
      this.formData = { description: [] }
      this.resetData()
      this._visible = false
    },
    handleServerChange(val) {
      this.uploadAddress = `http://${val.domain}${val.contextPath}/upload`
    },
    handleUploadCheck(file) {
      this.$refs['dataForm_version'].clearValidate(['pkg'])
      const name = file.name
      if (this.formData.product === undefined || this.formData.product.trim() === '') {
        return new Promise(() => {
          this.uploadStatus = 2
          this.uploadTip = '请输入产品名称！'
          this.uploadFileList = []
        })
      }
      if (!name.endsWith('.pkg')) {
        return new Promise(() => {
          this.uploadStatus = 2
          this.uploadTip = '请上传pkg格式的文件！'
          this.uploadFileList = []
        })
      }
      const size = (file.size / (1024 * 1024)).toFixed(2)
      if (size > 60) {
        return new Promise(() => {
          this.uploadStatus = 2
          this.uploadTip = '上传文件不能超过60M'
          this.uploadFileList = []
        })
      }
      this.formData.size = file.size
      this.formData.sizeText = `${size}MB`

      this.uploadData.product = this.formData.product
      return true
    },
    handleUploadSuccess(resp) {
      if (resp.status === apiConst.STATUS.STATUS_OK) {
        this.uploadStatus = 1
        this.uploadTip = '上传成功！'
        this.formData.uri = resp.data
      } else {
        this.uploadStatus = 2
        this.uploadTip = '上传失败！'
        this.uploadFileList = []
      }
    },
    handleUploadError(err) {
      console.log(`upload err:${JSON.stringify(err)}`)
      this.uploadStatus = 2
      this.uploadTip = '上传失败！'
      this.formData.uri = ''
    },
    handleUploadRemove() {
      this.uploadStatus = 0
      this.uploadTip = this.uploadDefaultTip
      this.formData.uri = ''
    },
    initRules() {
      const pkgCheck = (rule, value, callback) => {
        if (!this.formData.uri) {
          callback(new Error('请上传版本包'))
        } else {
          callback()
        }
      }

      const pkgExist = (rule, value, callback) => {
        if (this.formData.product && this.formData.version) {
          fota.existPkgByProductAndVersion({ product: this.formData.product, version: this.formData.version, flag: this.formData.flag }).then(resp => {
            if (resp.data === -1) { // id of the exist pkg
              callback()
            } else {
              callback(new Error('版本已存在，请修改产品名称、版本号或标识'))
            }
          }, () => {
            const msg = '服务器异常，请稍后再试或联系管理员'
            fota.notifyError(msg)
            callback(new Error(msg))
          })
        } else {
          callback()
        }
      }

      this.rules = {
        product: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { min: 2, max: 64, message: '请输入2位到64位长度的字符', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '请输入版本号', trigger: 'blur' },
          { min: 2, max: 64, message: '请输入2位到64位长度的字符', trigger: 'blur' }
        ],
        flag: [
          { validator: pkgExist, trigger: 'submit' }
        ],
        server: [{ required: true, message: '请选择上传服务器', trigger: 'blur' }],
        releaseTime: [{ required: true, message: '请选择版本发布日期', trigger: 'blur' }],
        pkg: [{ validator: pkgCheck, trigger: 'blur' }]
      }
    }
  }
}
</script>
